using System;
using System.Collections.Generic;
using CMS_Admin.Backend.Api.Entity;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using CMS_Admin.Backend.Api.ParamModel;
using Newtonsoft.Json;
using CMS_Admin.Backend.Api.Repository;
using CMS_Admin.Backend.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;

namespace CMS_Admin.Backend.Controllers
{
    /// <summary>
    /// 登入用户
    /// </summary>


    [Authorize]
    [ApiController]
    [Route("amend")]
    public class AmendController : ControllerBase
    {
        private IRepository<Users> _usersRespository;
        private IRepository<Roles> _userRoles;
        private TokenParameter _tokenParameter;
        private readonly IConfiguration _configuration;

        public AmendController(IConfiguration configuration, IRepository<Users> usersRespository, IRepository<Roles> userRoles)
        {
            _configuration = configuration;
            _usersRespository = usersRespository;
            _userRoles = userRoles;
            _tokenParameter = _configuration.GetSection("TokenParameter").Get<TokenParameter>();
        }

        /// <summary>
        /// 获取登入用户相关信息
        /// </summary>
        ///
        /// <returns></returns>

        [HttpGet("{id}")]
        public dynamic Get(int id)
        {

            var claims = base.HttpContext.AuthenticateAsync().Result
           .Principal.Claims.FirstOrDefault().Subject.Claims;

            var nickname = claims.FirstOrDefault(c => c.Type == "nickname")?.Value;
            var username = claims.FirstOrDefault(c => c.Type == "username")?.Value;
            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var useid = int.Parse(userid);

            var user = from users in _usersRespository.Table
                       join roles in _userRoles.Table on users.RolesId equals roles.Id
                       where users.Id == useid
                       select new
                       {
                           Id = users.Id,
                           Username = users.Username,
                           Password = users.Password,
                           Nickname = users.Nickname,
                           RoleName = roles.RoleName,
                           CreatedTime = users.CreatedTime

                       };

            if (user == null)
            {
                return new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定用户不存在"
                };

            }
            return new
            {
                Code = 200,
                Data = user,
                Msg = "获取用户列表成功^_^"
            };

        }




        /// <summary>
        /// 修改登入用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut()]
        public dynamic Put(NewAmend model)
        {
            var claims = base.HttpContext.AuthenticateAsync().Result
           .Principal.Claims.FirstOrDefault().Subject.Claims;

            var userid = claims.FirstOrDefault(c => c.Type == "id")?.Value;
            var useid = int.Parse(userid);

            var user = _usersRespository.GetById(useid);
            if (user != null)
            {
                // 判断是修改密码还是修改昵称
                if (!string.IsNullOrEmpty(model.Password)
                && !string.IsNullOrEmpty(model.OldPassword)
                && !string.IsNullOrEmpty(model.ConfigPassword))
                {
                    // 验证旧密码
                    if (user.Password == model.OldPassword)
                    {
                        // 验证确认密码
                        if (model.Password == model.ConfigPassword)
                        {

                            user.Password = model.Password;
                            user.UpdatedTime = DateTime.Now;

                            _usersRespository.Update(user);
                            return JsonHelper.Serialize(new
                            {
                                Code = 200,
                                Data = user,
                                Msg = string.Format("你修改登入用户的id为：{0}，已经修改成功，请注意查收", user.Id)
                            });
                        }
                        else
                        {

                            return JsonHelper.Serialize(new
                            {
                                Code = 200,
                                Data = "",
                                Msg = "两次密码不一致"
                            });
                        }
                    }
                    else
                    {
                        return JsonHelper.Serialize(new
                        {
                            Code = 200,
                            Data = "",
                            Msg = "旧密码不正确！"
                        });
                    }
                }
                else
                {
                    user.Nickname = model.Nickname;

                    user.UpdatedTime = DateTime.Now;

                    _usersRespository.Update(user);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = user,
                        Msg = string.Format("你修改登入用户的id为：{0}，已经修改成功，请注意查收", user.Id)
                    });
                }

            }
            else
            {
                return JsonHelper.Serialize(new
                {
                    Code = 1004,
                    Data = "",
                    Msg = "指定Id的登入用户不存在，请确认后重试"
                });
            }
        }





    }
}